let oldproduct = {} //当前商品对象
/**
 * 获取商品ID
 * @returns 
 */
function getProductId() {
    let url = location.href
    //http://localhost:3000/pages/productDetail.html?id=13
    let index = url.indexOf('?') + 1
    let param = url.substring(index) //id=1
    let id = param.split('=')[1]
    return id
}

function getProductdDetail() {
    let id = getProductId()
    $.ajax({
        url: 'http://api.yuguoxy.com/api/shop/find',
        type: 'get',
        data: {
            id
        },
        success: function (data) {
            console.log(data);
            if (data.resultCode == 1) {
                let product = data.resultInfo
                oldproduct = product //存储当前商品为全局
                loadProductDetail(product)
            }
        }
    })
}

/**
 * 动态渲染详情页面
 * @param {}} product 
 */
function loadProductDetail(product) {
    let detailStr = `<div class="g-left">
                        <div class="showbox">
                            <img src="${product.picture}" alt="">
                            <div class="mask"></div>
                        </div>
                        <ul>
                            <li class="active"><img src="${product.list[0]}" alt=""></li>
                            <li><img src="${product.list[1]}" alt=""></li>
                            <li><img src="${product.list[2]}" alt=""></li>
                            <li><img src="${product.list[3]}" alt=""></li>
                        </ul>
                     </div>
                     <div class="g-right">
                        <h2>${product.product}</h2>
                        <p>${product.detail}</p>
                        <p class="price">商品价格￥${product.price}</p>
                        <button class="add-cart">加入购物车</button>
                        <button class="look-cart">查看购物车</button>
                    </div>
                    <div class="glass-wrapper">
                        <img src="${product.picture}" alt="">
                    </div>
                    `

    $('.detail-wraper').html(detailStr)

    lookCart() //动态渲染页面之后绑定事件

    onGlass()

    onTab()
}
let xian1 = localStorage.getItem('USER')
let xian2 = JSON.parse(xian1)
function lookCart() {
    $('.look-cart').on('click', function () {
        location.href = './cart.html'
    })
    $('.add-cart').on('click', function () {
        if(xian2){
            addProduct()
        }
        else{
            alert('请先注册或登录')
            location.href = './productlist.html'
          
            return
        }
        
    })


}
/**
 * 加入购物车
 *   1. 根据当前商品ID判断购物车中是否已经添加该商品，如果已经添加数量加一,否则来着构造新商品添加
 * 
 */
function addProduct() {
    let id = getProductId() //当前商品ID
    let cartListStr = localStorage.getItem('JD_CART')
    let cartList = JSON.parse(cartListStr) || [] //购物车数组
    let product = cartList.find(item => item.id == id)
    if (product) {
        product.num++ //数量加一 
        product.singlePrice = (product.num * product.price).toFixed(2)
    } else {
        //新商品
        let newProduct = {
            id: oldproduct.id, 
            url: oldproduct.picture,
            name: oldproduct.shop,
            price: oldproduct.price,
            singlePrice: oldproduct.price,
            num: 1,
            state: false
        }
        cartList.push(newProduct)
    }

    localStorage.setItem('JD_CART', JSON.stringify(cartList))
    alert('加入购物车成功!')

}

//放大镜
function onGlass() {
    let showBox = document.querySelector('.showbox') //显示盒子
    let mask = document.querySelector('.mask') //遮罩层
    let glassBox = document.querySelector('.glass-wrapper') //放大区域
    let bigImg = document.querySelector('.glass-wrapper>img') //放大背景图片

    //计算比例
    let glassBoxWidth = parseInt(window.getComputedStyle(glassBox).width)
    let glassBoxHeight = parseInt(window.getComputedStyle(glassBox).height)

    let showBoxWidth = parseInt(window.getComputedStyle(showBox).width)
    let showBoxHeight = parseInt(window.getComputedStyle(showBox).height)

    let maskWidth = parseInt(window.getComputedStyle(mask).width)
    let maskHeight = parseInt(window.getComputedStyle(mask).height)

    let w = glassBoxWidth * showBoxWidth / maskWidth
    let h = glassBoxHeight * showBoxHeight / maskHeight

    bigImg.style.width = w + 'px'
    bigImg.style.height = h + 'px'

    //鼠标移动事件
    showBox.addEventListener('mousemove', function (e) {
        e = e || window.event
        let x = e.offsetX - $('.mask').width() / 2
        let y = e.offsetY - $('.mask').height() / 2


        //边界检查
        if (x < 0) {
            x = 0
        }
        if (x > showBox.offsetWidth - mask.offsetWidth) {
            x = showBox.offsetWidth - mask.offsetWidth
        }
        if (y < 0) {
            y = 0
        }
        if (y > showBox.offsetHeight - mask.offsetHeight) {
            y = showBox.offsetHeight - mask.offsetHeight
        }

        $('.mask').css({
            top: y,
            left: x
        })

        let maskWidth = parseInt(window.getComputedStyle(mask).width)
        let maskHeight = parseInt(window.getComputedStyle(mask).height)
        let glassBoxWidth = parseInt(window.getComputedStyle(glassBox).width)
        let glassBoxHeight = parseInt(window.getComputedStyle(glassBox).height)
        let moveX = x * glassBoxWidth / maskWidth
        let moveY = y * glassBoxHeight / maskHeight

        //移动背景图片
        bigImg.style.left = -moveX + 'px'
        bigImg.style.top = -moveY + 'px'

    })

    showBox.addEventListener('mouseover', function () {
        mask.style.display = 'block'
        glassBox.style.display = 'block'
    })
    showBox.addEventListener('mouseout', function () {
        mask.style.display = 'none'
        glassBox.style.display = 'none'
    })
}

function onTab() {
    let showImg = document.querySelector('.showbox>img') //显示盒子
    let bigImg = document.querySelector('.glass-wrapper>img') //放大背景图片
    let liEle = document.querySelectorAll('.g-left li')
    for (let i = 0; i < liEle.length; i++) {
        liEle[i].addEventListener('mouseover', function () {
            onClear()
            this.classList.add('active')
            showImg.setAttribute('src', oldproduct.list[i])
            bigImg.setAttribute('src', oldproduct.list[i])
        })
    }
}

function onClear() {
    let liEle = document.querySelectorAll('.g-left li')
    for (let i = 0; i < liEle.length; i++) {
        liEle[i].classList.remove('active')
    }
}

getProductdDetail()